<template>
  <div class="home">
    <div class="body">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="table-w">
            <div class="title">裁片列表</div>
            <el-table
              :data="stockList"
              :row-style="tableRowStyle"
              :header-cell-style="tableHeaderColor"
              highlight-current-row
              :row-class-name="tableCurrentRowStyle"
              @row-click="rowClick"
              style="width: 100%;font-size:26px;"
              height="15.3rem"
            >
              <el-table-column label="序号" width="60">
                <template slot-scope="scope">{{scope.$index + 1}}</template>
              </el-table-column>
              <el-table-column prop="SpecConfigName" label="尺码" align="center"></el-table-column>
              <el-table-column prop="ColorConfigName" label="颜色" width="100" align="center"></el-table-column>
              <el-table-column prop="CuttingTotal" label="包内裁片数" width="100" align="center"></el-table-column>
              <el-table-column prop="CuttingWeight" label="重量（克）" width="100" align="center"></el-table-column>
              <el-table-column prop="StockCount" label="数量（片）" width="90" align="center">
                <template slot-scope="scope">{{scope.row.StockCount}}</template>
              </el-table-column>
              <el-table-column prop="StockTime" label="时间" width="100" align="center">
                  <template slot-scope="scope">
                      {{$moment(scope.row.StockTime).format('HH:mm:ss')}}
                  </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="select-w">
            <div class="title">当前裁片信息</div>
            <div class="top-w" v-if="orderItem.CustomFlnkID">
              <div class="select">
                <div class="tit">厂家：</div>
                <div class="des">{{orderItem.CustomerName}}</div>
              </div>
              <div class="select">
                <div class="tit">合同：</div>
                <div class="des" style="margin-top:2px;">{{orderItem.OrderOuterCode}}</div>
              </div>
              <div class="select">
                <div class="tit">款式：</div>
                <div class="des">{{orderItem.StyleName}}</div>
              </div>
            </div>
            <div
              class="button"
              :class="orderItem.CustomFlnkID ? 'default' : ''"
              @click="customerToFzml()"
            >选择厂家</div>
          </div>

          <div class="mid-w">
            <div class="select">
              <div class="tit">颜色：</div>
              <div
                class="but"
                :class="selColor == item.ColorConfigID ? 'active' : ''"
                v-for="(item,index) in partObj.Color"
                :key="index"
                @click="selColor = item.ColorConfigID"
              >{{item.ColorConfigName}}</div>
              <div class="des" v-if="!partObj.Color">暂无</div>
            </div>
            <div class="select">
              <div class="tit">尺码：</div>
              <div
                class="but"
                :class="selSpec == item.SpecConfigID ? 'active' : ''"
                v-for="(item,index) in partObj.Spec"
                :key="index"
                @click="selSpec = item.SpecConfigID"
              >{{item.SpecConfigName}}</div>
              <div class="des" v-if="!partObj.Spec">暂无</div>
            </div>
          </div>

          <div class="bot-w">
            <div class="select" v-for="(item,index) in partObj.Part" :key="index">
              <div class="tit-btn" @click="selectParts(selPart,item.PartFlnkID)">{{item.PartName}}</div>
              <div
                class="but"
                :class="selPart.includes(i.Code) ? 'active' : ''"
                v-for="(i,k) in item.Cutting"
                :key="k"
                @click="selectPart(selPart,i.Code)"
              >{{i.CuttingName}}</div>
            </div>
            <div class="part-none" v-if="!partObj.Part">暂无部位</div>
          </div>

          <el-row>
            <el-col :span="16">
              <div class="info-w">
                <div class="line">
                  <div class="row">
                    <div class="tit">重量：</div>
                    <div class="button" @click="dialogShow = true" v-if="!weight">请称重</div>
                    <div class="des" v-if="weight">{{weight}}</div>
                    <div class="unit">克</div>
                  </div>
                  <div class="row">
                    <div class="tit">数量：</div>
                    <el-input
                      v-model="stockCount"
                      ref="stockCountInput"
                      placeholder="请输入条数"
                      style="width:140px"
                      @keyup.enter.native="stockCountEnter()"
                    ></el-input>
                    <div class="unit">片</div>
                  </div>
                  <div class="row">
                    <div class="tit">缸号/批号：</div>
                    <el-input
                      v-model="cylinderNo"
                      ref="cylinderNoInput"
                      placeholder="请输入缸号/批号"
                      style="width:140px"
                      @keyup.enter.native="inStorage()"
                    ></el-input>
                  </div>
                </div>

                <div class="send-w">
                  <div
                    class="button"
                    :class="weight ? 'default' : ''"
                    @click="dialogShow = true"
                    v-if="weight"
                  >重新称重</div>
                  <div class="button" @click="inStorage()">入库</div>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stack-w">
                <div class="title">
                  <span>垛号信息</span>
                  <div
                    class="button"
                    :class="barCode ? 'default' : ''"
                    @click="changeBarCodeShow()"
                  >
                    <span>垛号</span>
                    <span v-if="barCodeShow">{{barCode || '请点击输入'}}</span>
                    <span v-else>
                      <el-input
                        v-model="barCode"
                        placeholder="请输入垛号"
                        ref="barCodeInput"
                        style="width:120px;margin-top:-10px;"
                        @keyup.enter.native="barCodeEnter()"
                      ></el-input>
                    </span>
                  </div>
                </div>

                <div class="stack">
                  <el-table
                    :data="stackList"
                    :row-style="tableRowStyle"
                    :header-cell-style="tableHeaderColor"
                    :row-class-name="tableCurrentRowStyle"
                    highlight-current-row
                    style="width: 100%;font-size:26px;"
                    height="3.7rem"
                  >
                    <el-table-column prop="MaterielName" label="物料名称" align="center"></el-table-column>
                    <el-table-column
                      prop="MaterielClassName"
                      label="物料类型"
                      width="100"
                      align="center"
                    ></el-table-column>
                    <el-table-column prop="StockCount" label="数量" width="100" align="center">
                      <template
                        slot-scope="scope"
                      >{{scope.row.StockCount}}({{scope.row.StockUnitName}})</template>
                    </el-table-column>
                    <el-table-column prop="StockStr10" label="重量" width="100" align="center">
                      <template slot-scope="scope">{{scope.row.StockStr10}}(克)</template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <!-- 称重弹窗 -->
    <div class="dialogBox-w" v-show="dialogShow">
      <div class="dialogBox">
        <div class="close">
          <div class="el-icon-circle-close icon" @click="dialogShow = false" />
        </div>
        <div class="info-w" @mousedown="getFocus()">
          <div class="line">
            <div class="row">
              <div class="ftit">请称重：</div>
              <el-input
                v-model="weight"
                ref="weightInput"
                placeholder="请称重"
                style="width:140px"
                @keyup.enter.native="makeSure"
              ></el-input>
              <div class="unit">克</div>
            </div>
          </div>
          <div class="send-w">
            <div class="button" @click="dialogShow = false">关闭</div>
            <div class="button" @click="makeSure()">确定</div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="dialogVisible" class="menuModalBox">
      <dialogchangj
        :instoreType="params.instoreType"
        :instoreurl="params.instoreurl"
      ></dialogchangj>
    </div>

    <!-- 裁片详情信息 -->
    <div class="menuModalBox-w" v-show="cuttingShow">
      <div class="menuModalBox" style="width:600px;height:480px;">
        <div class="close">
          <div class="el-icon-circle-close icon" @click="cuttingShow = false" />
        </div>
        <div class="cutting" v-if="cuttingInfo.StockID">
          <div class="tit">{{cuttingInfo.StyleName}}</div>
          <ul>
            <li>
              <span>料号：</span>
              ({{cuttingInfo.MaterielsDetailCode}})
            </li>
            <li>
              <span>床次：</span>
              {{cuttingInfo.BedID}}
            </li>
            <li>
              <span>尺码：</span>
              {{cuttingInfo.SpecConfigName}}
            </li>
            <li>
              <span>颜色：</span>
              {{cuttingInfo.ColorConfigName}}
            </li>
            <li>
              <span>部位：</span>
              {{cuttingInfo.PartName}}
            </li>
            <li>
              <span>包内裁片：</span>
              {{cuttingInfo.CuttingTotal}}
            </li>
            <li>
              <span>数量：</span>
              {{cuttingInfo.StockCount}}
            </li>
            <li>
              <span>重量：</span>
              {{cuttingInfo.CuttingWeight}}
            </li>
            <li>
              <span>订单号：</span>
              {{cuttingInfo.POCode}}
            </li>
            <li>
              <span>入库时间：</span>
              {{cuttingInfo.StockTime}}
            </li>
            <li>
              <span>客户名称：</span>
              {{cuttingInfo.CustomerName}}
            </li>
          </ul>
          <div class="button" @click="print()" v-if="cuttingInfo.StockID">重新打印</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import dialogchangj from '@/components/dialogchangj' // 厂家弹出框
import Mixin from '@/components/mixin' // 混入
import {getCuttingList, getStockList, getKCNumber, inStorage, getFabricInStockDesign, getProductStockListByBarCode} from '@/api/instorage' // 接口
import {GetShopCuttingInStockDesignByStock} from '@/api/tailoring'

export default {
  name: 'fzfl',
  data () {
    return {
      stockID: '',
      stockList: [],
      detailList: [],
      matter: '',
      matterInfo: '',
      weight: '', // 重量
      cylinderNo: '',
      setInterval: null,
      dialogShow: false,
      dialogVisible: false,
      params: {
        instoreType: '',
        instoreurl: ''
      },
      selDetail: '',
      stockCount: '',
      barCodeShow: true,
      barCode: '',
      checkDialog: false,
      selColor: '',
      selSpec: '',
      selPart: [],
      partObj: {},
      cuttingShow: false,
      cuttingInfo: '',
      stackList: [],
      materielType: '',
      isInStock: false
    }
  },
  computed: {
    ...mapState({
      orderItem: (state) => state.dialogchangj.orderItem
    })
  },
  mixins: [Mixin],
  components: {
    dialogchangj: dialogchangj
  },
  methods: {
    // 修改table tr行的背景色
    tableRowStyle ({ row, rowIndex }) {
      return {
        backgroundColor: 'rgb(0, 63, 140)',
        color: '#fff',
        fontWeight: 'bold',
        height: '0.7rem',
        fontSize: '15px'
      }
    },
    tableCurrentRowStyle ({ row, rowIndex }) {
      let vm = this
      if (vm.isInStock) {
        if (rowIndex === 0) {
          return 'warning-row'
        }
      } else {
        return 'normal-row'
      }
    },
    // 修改table header的背景色
    tableHeaderColor ({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: rgb(0, 63, 140);color: #fff;font-weight: bold;height:0.7rem;font-size:15px'
      }
    },
    // 裁片入库-根据款式读取裁片入库物料列表
    getCuttingMaterielDetailByStyle () {
      let vm = this
      let params = new FormData()
      params.append('StyleFlnkID', vm.orderItem.StyleFlnkID)
      getCuttingList(params).then((response) => {
        if (response.data.data) {
          vm.partObj = response.data.data
        }
      })
    },
    // 读取今日最新面料入库列表
    getStockList () {
      let vm = this
      let params = new FormData()
      params.append('TopCount', 20)
      params.append('UserFlnkID', vm.getLocalStorage('UserFlnkID'))
      params.append('Type', vm.materielType.slice(0, 1))
      getStockList(params).then((response) => {
        vm.stockList = response.data.data
      })
    },
    // 读取入库单
    async getKCNumber () {
      let vm = this
      let params = {
        ShortName: 'CK'
      }
      await getKCNumber(params).then((response) => {
        if (response.data) {
          vm.stockID = response.data
        }
      })
    },
    // 入库记账
    async inStorage () {
      let vm = this
      if (!vm.matterInfo.CustomFlnkID) {
        vm.$message('请选择厂家')
        return
      }

      if (!vm.selColor) {
        vm.$message('请选择颜色')
        return
      }

      if (!vm.selSpec) {
        vm.$message('请选择尺码')
        return
      }

      if (vm.selPart.length === 0) {
        vm.$message('请选择部位')
        return
      }

      if (vm.weight === '') {
        vm.$message('请称重')
        return
      }
      if (vm.stockCount === '') {
        vm.$message('请输入数量')
        return
      }

      // 获取一个新的入库单号
      await vm.getKCNumber()
      // 格式化入参
      let cuttings = vm.formaterCuttings()

      let params = {
        StockID: vm.stockID,
        CustomerFlnkID: vm.matterInfo.CustomFlnkID,
        OrderOuterCode: vm.matterInfo.OrderOuterCode,
        StyleFlnkID: vm.matterInfo.StyleFlnkID,
        CuttingWeight: vm.weight,
        StockCount: vm.stockCount,
        StockUnitFlnkID: vm.partObj.UnitID,
        WarehouseFlnkID: vm.warehouseFormat(vm.materielType.slice(0, 1)),
        CylinderNo: vm.cylinderNo,
        BarCode: vm.barCode,
        OrgID: vm.getLocalStorage('OrgID'),
        OperFlnkID: vm.getLocalStorage('UserFlnkID'),
        ColorConfigID: vm.selColor,
        SpecConfigID: vm.selSpec,
        Cuttings: cuttings
      }
      // console.log(JSON.stringify(params));
      inStorage(params).then((response) => {
        if (response.data.result) {
          let params1 = new FormData()
          // 根据裁片编号获取裁片信息  自裁片等等
          params1.append('StockID', vm.stockID)
          getFabricInStockDesign(params1).then((response) => {
            if (response.data.result) {
              var info = response.data.data
              if (vm.isAndroid()) {
                window.android.print('CK', JSON.stringify(info))
              } else {
                vm.$message(JSON.stringify(info))
              }
            }
          })
          vm.getStockList()
          vm.getProductStockListByBarCode()
          vm.isInStock = true
          vm.$message(response.data.error)
        } else {
          vm.$message(response.data.error)
        }
      })
    },
    // 格式化部位入参结构
    formaterCuttings () {
      let vm = this
      let tempArr = []
      vm.partObj.Part.map((item) => {
        for (let i = 0; i < item.Cutting.length; i++) {
          let _temp = {}
          if (vm.selPart.includes(item.Cutting[i].Code)) {
            _temp = {
              PartFlnkID: item.PartFlnkID,
              PartName: item.PartName,
              CuttingCode: item.Cutting[i].Code,
              CuttingName: item.Cutting[i].CuttingName
            }
          } else {
            break
          }
          tempArr.push(_temp)
        }
      })
      return tempArr
    },
    // 裁片入库-读取裁片入库明细的存货标签
    getFabricInStockDesign () {
      let vm = this
      let params = new FormData()
      params.append('StockID', vm.stockID)
      getFabricInStockDesign(params).then((response) => {
        vm.cuttingInfo = response.data.data
      })
    },
    // 单击表格某一行
    rowClick (row) {
      let vm = this
      vm.stockID = row.StockID
      vm.isInStock = false
      vm.getFabricInStockDesign()
      vm.cuttingShow = true
    },
    // 打印标签
    print () {
      let vm = this
      let params = new FormData()
      debugger
      if (vm.isAndroid()) {
        params.append('StockID', vm.cuttingInfo.StockID)
        if (vm.cuttingInfo.CuttingTypeName === '自裁裁片') {
          GetShopCuttingInStockDesignByStock(params).then((response) => {
            if (response.data.result) {
              if (vm.isAndroid()) {
                window.android.print('CZ', JSON.stringify(response.data.data))
              } else {
                vm.$message(JSON.stringify(response.data.data))
              }
            }
          })
        } else {
          getFabricInStockDesign(params).then((response) => {
            if (response.data.result) {
              var info = []
              info.push(response.data.data)
              if (vm.isAndroid()) {
                window.android.print('CW', JSON.stringify(info))
              } else {
                vm.$message(JSON.stringify(info))
              }
            }
          })
        }
      } else {
        vm.$message(JSON.stringify(vm.cuttingInfo))
      }
      vm.cuttingShow = false
    },
    customerToFzml () {
      let vm = this
      vm.params = {
        instoreType: vm.materielType,
        instoreurl: '/instorage/fzcp'
      }
      vm.dialogVisible = true
    },
    getWindowClose: function () {
      let vm = this
      vm.dialogVisible = false
    },
    makeSure () {
      let vm = this
      if (vm.weight) {
        vm.dialogShow = false
        vm.$refs.stockCountInput.focus()
      } else {
        vm.$message('请称重')
      }
    },
    changeBarCodeShow () {
      let vm = this
      vm.barCodeShow = false
      vm.barCode = ''
      vm.$nextTick(() => {
        vm.$refs.barCodeInput.focus()
      })
    },
    // 选中/取消部位
    selectPart (arr, id) {
      if (arr.includes(id)) {
        for (let key in arr) {
          if (arr[key] === id) {
            arr.splice(key, 1)
          }
        }
      } else {
        arr.push(id)
      }
    },
    // 全选当前部位
    selectParts (arr, id) {
      let vm = this
      let tempArr = []
      tempArr = vm.partObj.Part.filter((item) => {
        return item.PartFlnkID === id
      })[0]

      let isAllSel = tempArr.Cutting.every((item) => {
        return arr.includes(item.Code)
      })

      tempArr.Cutting.map((item) => {
        if (isAllSel) {
          for (let key in arr) {
            if (arr[key] === item.Code) {
              arr.splice(key, 1)
            }
          }
        } else if (!arr.includes(item.Code)) {
          arr.push(item.Code)
        }
      })
    },
    barCodeEnter () {
      let vm = this
      vm.getProductStockListByBarCode()
      vm.barCodeShow = true
    },
    stockCountEnter () {
      let vm = this
      vm.$refs.cylinderNoInput.focus()
    },
    // 公共接口-根据垛号读取库存记录列表
    getProductStockListByBarCode () {
      let vm = this
      let params = new FormData()
      params.append('BarCode', vm.barCode)
      getProductStockListByBarCode(params).then((response) => {
        if (response.data.result) {
          vm.stackList = response.data.data
        } else {
          vm.$message(response.data.error)
        }
      })
    }
  },
  watch: {
    orderItem: {
      // 表格数据刷新后需清空之前查看的订单详情内容
      handler: function (newVal, oldVal) {
        let vm = this
        vm.getCuttingMaterielDetailByStyle()
        vm.matterInfo = newVal
      },
      deep: true
    },
    dialogShow (newVal, oldVal) {
      let vm = this
      if (newVal === true) {
        vm.$nextTick(() => {
          vm.$refs.weightInput.focus()
        })
      }
    },
    getFocus () {
      let vm = this
      vm.$nextTick(() => {
        vm.$refs.weightInput.focus()
      })
    }
  },
  mounted () {
    let vm = this
    vm.setInterval = setInterval(() => {
      if (vm.getLocalStorage('UserFlnkID')) {
        vm.getStockList()
        clearInterval(vm.setInterval)
        vm.setInterval = null
      }
    }, 1000)
    setTimeout(() => {
      vm.getCuttingMaterielDetailByStyle()
      vm.matterInfo = vm.orderItem
    }, 0)
    vm.materielType = vm.$route.query.type
  },
  beforeDestroy: function () {}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import "~@/css/instorage/fzcp.scss";
</style>
<style lang="scss">
.info-w,
.stack-w {
  .el-input__inner {
    background: #002752;
    color: #fff;
  }
}
.el-table .warning-row {
	background: #002752 !important;
}
.el-table .normal-row{
    background: rgb(0, 63, 140) !important;
}
.el-table::before {
    height: 0px;
 }
</style>
